package edu.seu.mart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.seu.mart.entity.Pager;
import edu.seu.mart.model.*;
import edu.seu.mart.model.dto.OrderDto;
import edu.seu.mart.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by samsung on 2015/3/25.
 */
@Controller
@RequestMapping("/weixin")
public class UserController {

    @Resource
    private IGoodsService goodsService;

    @Resource
    private ICartService cartService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderItemService orderItemService;

    @Resource
    private IAddressService addressService;

    private static List<OrderDto> orderDtos;

    /**
     * 微商城首页
     */
    @RequestMapping(value = {"/", "/index"})
    public String index(Model model) {
        List<Goods> list1 = goodsService.findGoodsByCategory("bjb").getDatas();
        List<Goods> list2 = goodsService.findGoodsByCategory("tsj").getDatas();
        List<Goods> list3 = goodsService.findGoodsByCategory("pb").getDatas();
        List<Goods> bjb = new ArrayList<>();
        List<Goods> tsj = new ArrayList<>();
        List<Goods> pb = new ArrayList<>();
        for (int i = 0; i < 4; i ++) {
            System.out.println(list1.get(i).getId());
            bjb.add(list1.get(i));
            tsj.add(list2.get(i));
            pb.add(list3.get(i));
        }
        model.addAttribute("bjb", bjb);
        model.addAttribute("tsj", tsj);
        model.addAttribute("pb", pb);
        return "index";
    }

    @RequestMapping("/all")
    public String all(Model model) {
        // 1 表示正售商品
        model.addAttribute("goodsList", goodsService.findGoodsList(1));
        return "allGoods";
    }

    /**
     * 商品详情页
     */
    @RequestMapping(value = "/{id}/single", method = RequestMethod.GET)
    public String show(@PathVariable int id, Model model) {
        Goods goods = goodsService.load(id);
        model.addAttribute("goods", goods);
        List<String> fourImageList = new ArrayList<>();
        String fourImageStr = goods.getFourImage();
        if (fourImageStr != null) {
            Collections.addAll(fourImageList, fourImageStr.split(";"));
        }
        List<String> detailImageList = new ArrayList<>();
        String detailImageStr = goods.getDetailImage();
        if (detailImageStr != null) {
            Collections.addAll(detailImageList, detailImageStr.split(";"));
        }
        model.addAttribute("fourImageList", fourImageList);
        model.addAttribute("detailImageList", detailImageList);
        return "goods";
    }

    /**
     * 购物车列表
     */
    //TODO userId
    @RequestMapping("/cart")
    public String cart(Model model) {
        model.addAttribute("carts", cartService.findUserCart(1));
        return "cart";
    }

    /**
     * 添加到购物车
     */
    //TODO userId
    @RequestMapping(value = "/addToCart", method = RequestMethod.POST)
    public void addToCart(@RequestParam int goodsId, @RequestParam int goodsnum,
                          HttpServletResponse resp) throws IOException {
        Goods goods = goodsService.load(goodsId);
        Cart cart = new Cart(goods, 1, goods.getPrice() * goodsnum, goodsnum);
        cartService.add(cart);
        resp.getWriter().print("sucess");
    }

    /**
     * 购物车删除
     */
    @RequestMapping(value = "/{id}/cartdelete", method = RequestMethod.GET)
    public String deleteCart(@PathVariable int id) {
        cartService.delete(id);
        return "redirect:/weixin/cart";
    }

    /**
     * 购物车清空
     */
    @RequestMapping(value = "/clearCart", method = RequestMethod.GET)
    public String clearCart() {
        return null;
    }

    /**
     * 提交订单
     */
    //TODO userId
    @RequestMapping(value = "/orderCommit", method = RequestMethod.POST)
    public String orderCommit(@RequestParam String orderjson, Model model) {
        JSONObject object = JSON.parseObject(orderjson);
        Double totalprice = object.getDouble("totalprice");
        List<Map<String, Integer>> list = (List<Map<String, Integer>>) object.get("goods");
        orderDtos = new ArrayList<>();
        int totalnum = 0;
        for (Map<String, Integer> map : list) {
            Integer cartid = map.get("cartid");
            Integer quantity = map.get("quantity");
            Goods goods = cartService.load(cartid).getGoods();
            OrderDto orderDto = new OrderDto();
            orderDto.setCartId(cartid);
            orderDto.setSellerId(goods.getSeller().getId());
            orderDto.setSellerName(goods.getSeller().getName());
            orderDto.setGoodsId(goods.getId());
            orderDto.setGoodsImg(goods.getImage());
            orderDto.setGoodsName(goods.getName());
            double price = goods.getPrice();
            orderDto.setPrice(price);
            orderDto.setQuantity(quantity);
            orderDto.setSubtotal(quantity * price);
            orderDto.setUserId(1);
            totalnum += quantity;
            orderDtos.add(orderDto);
        }
        model.addAttribute("totalprice", totalprice);
        model.addAttribute("totalnum", totalnum);
        model.addAttribute("orderDtos", orderDtos);
        return "order";
    }

    /**
     * 生成订单
     */
    //TODO AddressID
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public String addOrder() {
        if (orderDtos != null) {
            Map<Integer, List<OrderDto>> map = new HashMap<>();
            for (OrderDto dto : orderDtos) {
                int sellerId = dto.getSellerId();
                if (!map.keySet().contains(sellerId)) {
                    List<OrderDto> list = new ArrayList<>();
                    list.add(dto);
                    map.put(sellerId, list);
                } else {
                    map.get(sellerId).add(dto);
                }
            }
            List<Integer> cartIds = new ArrayList<>();
            for (Integer sellerId : map.keySet()) {
                List<OrderDto> list = map.get(sellerId);
                boolean flag = true;
                Order order = new Order();
                Set<OrderItem> set = new HashSet<>();
                double total = 0;
                for (OrderDto dto : list) {
                    if (flag) {
                        order.setSeller_id(dto.getSellerId());
                        order.setUser_id(dto.getUserId());
                        order.setState("待付款");
                        order.setOrderdate(new Date());
                        Address address = addressService.findAddressById(1);
                        order.setAddress(address);
                        flag = false;
                    }
                    OrderItem orderItem = new OrderItem();
                    double sub = dto.getSubtotal();
                    total += sub;
                    orderItem.setSubtotal(sub);
                    orderItem.setGoods(goodsService.load(dto.getGoodsId()));
                    orderItem.setQuantity(dto.getQuantity());
                    cartIds.add(dto.getCartId());
                    set.add(orderItem);
                    orderItemService.add(orderItem);
                }
                order.setTotal(total);
                order.setOrderItems(set);
                orderService.add(order);
            }
            System.out.println("订单生成成功！");
            cartService.delete(cartIds);
        }
        return "redirect:/weixin/userOrders";
    }

    /**
     * 订单页面
     */
    //TODO userId
    @RequestMapping("/userOrders")
    public String order(Model model) {
        model.addAttribute("orders", orderService.loadByUserId(1));
        return "userOrders";
    }

    /**
     * 用户中心
     */
    @RequestMapping("/usercenter")
    public String usercenter() {
        return "usercenter";
    }
}
